package com.mtgdeckbuilder.server.dao;

import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.mtgdeckbuilder.server.EMF;
import com.mtgdeckbuilder.server.entity.Deck;

/**
 * The Data Access Object for a deck.
 * 
 * @author Nicolas Deslandes
 */
public class DeckDAO extends DAO<Deck> {

   private static Logger logger = Logger.getLogger(DeckDAO.class.getName());

   @SuppressWarnings("unchecked")
   @Override
   public List<Deck> query(final Deck args) {
      logger.finest("Call of query(" + args + ")");
      final EntityManager em = EMF.get().createEntityManager();
      try {
         final Query query = em.createQuery("select from " + Deck.class.getName());
         final List<Deck> decks = query.getResultList();
         decks.size();
         for (final Deck deck : decks) {
            deck.getCards().size();
         }
         return decks;
      } finally {
         em.close();
      }
   }

   @Override
   public Deck fetch(final long id) {
      logger.finest("Call of fetch(" + id + ")");
      final Key key = KeyFactory.createKey(Deck.class.getSimpleName(), id);
      return fetch(key);
   }

   @Override
   public Deck fetch(final Key key) {
      logger.finest("Call of fetch(" + key + ")");
      final EntityManager em = EMF.get().createEntityManager();
      try {
         return em.find(Deck.class, key);
      } finally {
         em.close();
      }
   }
}
